package com.luocc.tim.utils;

import android.content.Context;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class TimUtils {

    public static final String TAG = "TimUtils";
    /**
     * 用SimpleDateFormat计算时间差
     */
    @NonNull
    public static String getDateString(@NonNull Date source) {
        String dateString = "";
        long sourceTime = source.getTime();
        long currentTimeMillis = System.currentTimeMillis();
        int days = (int) ((currentTimeMillis - sourceTime) / (1000 * 60 * 60 * 24));
        SimpleDateFormat simpleDateFormat;
        switch (days) {
            case 0:
                simpleDateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
                return simpleDateFormat.format(source);
            case 1:
                dateString = "昨天";
                return dateString;
            case 2:
                dateString = "前天";
                return dateString;
            default:
                simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                return simpleDateFormat.format(source);
        }
    }

    /**
     * 判断点击事件的坐标是否处于view范围
     * @param view view
     * @param event 事件
     * @return true if contains
     */
    public static boolean eventInView(View view, MotionEvent event) {
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        Log.d(TAG, "eventInView: location[" + location[0] + ", " + location[1] + "]");
        int left = location[0];
        int top = location[1];
        int right = location[0] + view.getWidth();
        int bottom = location[1] + view.getHeight();
        float x = event.getRawX();
        float y = event.getRawY();
        Log.d(TAG, "eventInView: [" + left + ", " + top + ", " + right + ", " + bottom + "], [" + x + ", " + y + "]");
        return left < right && top < bottom  // check for empty first
                && x >= left && x < right && y >= top && y < bottom;
    }

    public static int dip2px(@NonNull Context content, int dp) {
        float density = content.getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5);
    }

    public static int px2dip(@NonNull Context content, int px) {
        float density = content.getResources().getDisplayMetrics().density;
        return (int) (px / density + 0.5);
    }
}
